package com.ssb.plugins;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apache.cache.util.Validator;
import com.apache.exception.BusinessException;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.tools.DataMap;
import com.apache.tools.DateUtils;
import com.apache.tools.MD5Utils;
import com.apache.tools.StrUtil;
import com.ssb.service.check.CheckedFrontSysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 黄河接口对接-电子发票
 */
@Component
public class HheRlectronicInvoice extends HheSuperPlugin {


    @Autowired
    private CheckedFrontSysService checkedFrontSysService;

    @Override
    public Object beforeInvoke(Map<String, Object> map) {

        //校验此前端系统是否存在且有效
        String frontSysCode = StrUtil.doNull(String.valueOf(map.get("frontSysCode")));
        Map<String,String> result =  checkedFrontSysService.checkedSysByFrontSysCode(frontSysCode);
        if (result.get("errorCode").equals("F")){
            throw new BusinessException("此系统有误：" + result.get("errorMsg"));
        }

        String infoId=String.valueOf(map.get("infoId"));
        if(StrUtil.isNull(infoId)){
            throw new BusinessException("订单ID不能为空");
        }
        Object obj = getOrderById(infoId);
        if(!Validator.isEmpty(obj)){
            map.put("orderInfo",obj);
            customMethod(map);
        }
        return null;
    }

    @Override
    public Object afterInvoke(Map<String, Object> map) {
        customMethod(map);
        return null;
    }

    private void customMethod(Map<String, Object> map) {
        long startLong = System.currentTimeMillis();
        Map<String, Object> param = new HashMap<>();
        Map<String, Object> head = new HashMap<>();
        Map<String, Object> body = new HashMap<>();
        DataMap<String> orderInfo = (DataMap)map.get("orderInfo");
        if(StrUtil.isNotNull(String.valueOf(orderInfo.get("invoiceNo")))){
            map.put("resultData",downLoad(orderInfo.get("infoId")));
            return ;
        }
        head.put("platform",StrUtil.doNull(String.valueOf(orderInfo.get("channelId")),"SSK"));//平台标示（默认SSK）
        head.put("requestType","50");//50电子发票 请求类型（10：投保单：30：电子保单；40：保单生成通知，50：电子发票）
        String transactionNo = Validator.generate();
        head.put("transactionNo",transactionNo);//请求事务编号，用于区别是那一次的请求
        head.put("md5Value", MD5Utils.MD5(transactionNo + ""));//32位的编码结果, 另外约定的密码 进行MD5编码
        head.put("timeStamp", DateUtils.Now.fmt_yyyyMMdd_HHmmss());//时间戳
        head.put("errorCode","0000");//0000：成功
        head.put("errorMsg","成功");//错误描述，无异常返回“成功”（默认成功）

        List<Map> invoiceTargets = new ArrayList<>();
        Map<String, Object> inv = new HashMap<>();
        inv.put("policyNo",orderInfo.get("policyNo"));//保单号
        inv.put("invoiceTitle",StrUtil.doNull(String.valueOf(map.get("invoiceTitle")),String.valueOf(orderInfo.get("applicantName"))));//发票抬头
        inv.put("taxpayerId",StrUtil.doNull(String.valueOf(map.get("taxpayerId")),String.valueOf(orderInfo.get("applicantCertiNo"))));//纳税人识别号
        Map<String, Object> invoiceExt = new HashMap<>();
        invoiceExt.put("isMerge",map.get("isMerge"));//是否合并开票 0-否  1-是
        invoiceExt.put("productCode",orderInfo.get("productId"));//产品代码
        String invoiceType = StrUtil.doNull(String.valueOf(map.get("invoiceType")),"2");
        if("2".equals(orderInfo.get("applicantType"))){
            invoiceType = StrUtil.doNull(String.valueOf(map.get("invoiceType")),"1");
        }
        invoiceExt.put("invoiceType",invoiceType);//发票类型  传值为：1：增值税普通发票（公司）2：增值税普通发票（个人）3：增值税专用发票传值为2时取的是承保的投保人姓名节点
        invoiceExt.put("amount", StrUtil.doNull(String.valueOf(map.get("amount")),"1"));//保单数量(保单数量，最大为500),默认1
        inv.put("invoiceExt",invoiceExt);//扩展
        invoiceTargets.add(inv);
        body.put("invoiceTargets",invoiceTargets);

        param.put("head",head);
        param.put("body",body);
        String str = String.valueOf(sendInterface("Externalcommon/surrenderSSK", param,null));
        log.info("电子发票结果："+str);
        if(Validator.isNotNull(str)) {//处理接口返回结果
            JSONObject json = JSON.parseObject(str);
            if("0000".equals(json.getJSONObject("head").getString("errorCode"))){
                JSONArray array = json.getJSONObject("body").getJSONArray("invoiceResults");
                String infoId = String.valueOf(orderInfo.get("infoId"));
                String sql = "update ss_insur_order set ";
                for(int i=0;i<array.size();i++){
                    JSONObject obj = array.getJSONObject(i);
                    if("0000".equals(obj.getString("errorCode"))) {
                        StringBuilder sb = new StringBuilder(sql);
                        sb.append("invoice_no='"+obj.getString("invoiceNo")+"',");
                        sb.append("invoice_amount='"+obj.getString("invoiceAmount")+"',");
                        sb.append("invoice_down_url='"+obj.getString("downloadUrl")+"',");
                        sb.append("invoice_time='"+obj.getString("invoiceTime")+"'");
                        sb.append(" where info_id='"+infoId+"'");
                        IusPluginUtil.getInstance().saveInvoke("",sb.toString());
                    }
                }
            }
            map.put("resultData",json);
        }
        log.info("huanghe interface exetime = "+(System.currentTimeMillis()-startLong)+" ms");
    }

    private Map downLoad(String infoId){
        String sql = "select info_id, invoice_down_url,invoice_time,invoice_no from ss_insur_order where info_id='"+infoId+"'";
        List list = select(sql,DATA_SOURCE);
        Map data = new HashMap();
        net.sf.json.JSONObject head = new net.sf.json.JSONObject();
        head.put("errorCode", "0001");
        head.put("timeStamp", DateUtils.Now.fmt_yyyyMMdd_HHmmss());
        head.put("errorMsg","下载电子发票失败");
        if(!Validator.isEmpty(list)){
            Map obj = (Map)list.get(0);
            if(Validator.isNotNull(String.valueOf(obj.get("invoiceDownUrl")))){
                List<Map> lists = new ArrayList(1);
                Map body = (Map)list.get(0);
                body.put("errorMsg","下载电子发票成功");
                body.put("errorCode", "0000");
                body.put("downloadUrl",body.get("invoiceDownUrl"));
                lists.add(body);
                Map bodys = new HashMap();
                bodys.put("invoiceResults",lists);
                data.put("body",bodys);
                head.put("errorMsg","下载电子发票成功");
                head.put("errorCode", "0000");
            }else {
                head.put("errorMsg", "电子发票上未开据");
            }
        }
        data.put("head",head);
        return data;
    }
}
